/*
 * Copyright © Yan Zhenjie. All Rights Reserved
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.iotimc.attendancesystem.server.response;

import android.text.TextUtils;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.iotimc.attendancesystem.App;
import com.iotimc.attendancesystem.dao.AttendanceLogEntityDao;
import com.iotimc.attendancesystem.dao.DoorLogEntityDao;
import com.iotimc.attendancesystem.dao.GreenDaoManager;
import com.iotimc.attendancesystem.dao.PersonEntityDao;
import com.iotimc.attendancesystem.entity.AttendanceLogEntity;
import com.iotimc.attendancesystem.entity.PersonEntity;
import com.iotimc.attendancesystem.util.JxlWriteExcel;
import com.iotimc.attendancesystem.util.WriteExcelUtils;
import com.iotimc.networklibrary.entity.BaseEntity;
import com.yanzhenjie.andserver.RequestHandler;
import com.yanzhenjie.andserver.util.HttpRequestParser;

import org.apache.commons.io.Charsets;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.protocol.HttpContext;
import org.apache.poi.ss.usermodel.Workbook;
import org.greenrobot.greendao.query.QueryBuilder;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;

/**
 * @author david
 */
public class RequestLogHandler implements RequestHandler {
    private static final String TAG = "RequestLogHandler";

    // SimplePropertyPreFilter filter = new SimplePropertyPreFilter(实体类.class, "字段1","字段2");


    @Override
    public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException {
        Map<String, String> params = HttpRequestParser.parse(request);
        Log.i(TAG, "Params: " + params);
        String action = params.get("action");
        String xls = params.get("xls");
        String search = params.get("search");
        // 数据起始位置
        String start = params.get("start");
        // 数据长度 每页多少条数据
        String length = params.get("length");
        // 转换分页参数
        int pageSize = Integer.parseInt(length);
        int pageNum = Integer.parseInt(start) / pageSize + 1;
        QueryBuilder queryBuilder = null;
        switch (action) {
            case "attendanceLog":
                queryBuilder = GreenDaoManager.getInstance().getSession().getAttendanceLogEntityDao().queryBuilder().
                        orderDesc(AttendanceLogEntityDao.Properties.CreateTime);
                if (!TextUtils.isEmpty(search)) {
                    queryBuilder.join(AttendanceLogEntityDao.Properties.PersonId, PersonEntity.class,
                            PersonEntityDao.Properties.Id)
                            .whereOr(PersonEntityDao.Properties.Code.like("%" + search + "%")
                                    , PersonEntityDao.Properties.Name.like("%" + search + "%"));
                }
                break;
            case "doorLog":
                queryBuilder = GreenDaoManager.getInstance().getSession().getDoorLogEntityDao().queryBuilder().
                        orderDesc(DoorLogEntityDao.Properties.CreateTime);
                if (!TextUtils.isEmpty(search)) {
                    queryBuilder.join(AttendanceLogEntityDao.Properties.PersonId, PersonEntity.class,
                            PersonEntityDao.Properties.Id)
                            .whereOr(PersonEntityDao.Properties.Code.like("%" + search + "%")
                                    , PersonEntityDao.Properties.Name.like("%" + search + "%"));
                }
                break;
            default:

                break;
        }
        if (TextUtils.isEmpty(xls)) {
            int count = 0;
            List data = null;
            if (queryBuilder != null) {
                data = queryBuilder.offset((pageNum - 1) * pageSize).limit(pageSize).list();
                count = (int) queryBuilder.count();
            }

            BaseEntity<List> baseEntity = new BaseEntity<>();
            baseEntity.setMessage("同步成功");
            baseEntity.setStatus("0");
            baseEntity.setResult(data);
            baseEntity.setRecordsTotal(count);
            baseEntity.setTime(System.currentTimeMillis());
            StringEntity stringEntity = new StringEntity(JSON.toJSONString(baseEntity,
                    SerializerFeature.DisableCircularReferenceDetect, SerializerFeature.WriteDateUseDateFormat), "utf-8");
            response.setEntity(stringEntity);
        } else {
            switch (action) {
                case "attendanceLog":
                    writeWork(response, JxlWriteExcel.excel(queryBuilder.list()), "验证记录");
                    break;

                case "doorLog":
                    writeWork(response, WriteExcelUtils.createDoorLogExcel(queryBuilder.list()), "开门记录");
                    break;
                default:
                    break;
            }
        }
    }

    private void writeWork(HttpResponse response, byte[] bytes, String name) {
        response.setHeader("Content-Type", "application/vnd.ms-excel");
        try {
            response.addHeader("Content-Disposition", "attachment;filename=" +
                    java.net.URLEncoder.encode(name, "UTF-8") + ".xls");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        response.setEntity(new ByteArrayEntity(bytes));
    }

    private void writeWork(HttpResponse response, Workbook workbook, String name) {
        response.setHeader("Content-Type", "application/vnd.ms-excel");
        try {
            response.addHeader("Content-Disposition", "attachment;filename=" +
                    java.net.URLEncoder.encode(name, "UTF-8") + ".xls");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            workbook.write(os);
            byte[] bytes = os.toByteArray();
            response.setEntity(new ByteArrayEntity(bytes));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
